package com.intermancer.predictor.lifecycle;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.chain.Context;

public abstract class LifecycleCommandBase implements LifecycleCommand {
	
	private List<LifecycleListener> listeners;
	
	abstract boolean innerExecute(LifecycleContext context);
	
	@Override
	public boolean execute(Context context) throws Exception {
		LifecycleContext lifecycleContext = (LifecycleContext) context;
		boolean returnValue = innerExecute(lifecycleContext);
		if(listeners != null) {
			for(LifecycleListener listener : listeners) {
				listener.handleEvent(lifecycleContext);
			}
		}
		return returnValue;
	}

	@Override
	public void addLifecycleListener(LifecycleListener listener) {
		if (listeners == null) {
			listeners = new ArrayList<LifecycleListener>();
		}
		if (listener != null) {
			listeners.add(listener);
		}
	}

	@Override
	public void setLifecycleListeners(List<LifecycleListener> listeners) {
		this.listeners = listeners;
	}

}
